package com.yhy.common.rabbitmq.config;

import com.yhy.common.rabbitmq.callback.ConfirmCallback;
import com.yhy.common.rabbitmq.callback.ReturnsCallback;
import com.yhy.common.rabbitmq.dynamic.RabbitModuleInitializer;
import com.yhy.common.rabbitmq.dynamic.RabbitModuleProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;


@Slf4j
@ComponentScan("com.yhy.common.rabbitmq")
public class RabbitConfig {

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    @ConditionalOnMissingBean
    public ConfirmCallback defaultConfirmCallback() {
        return new ConfirmCallback() {
            @Override
            protected void compensate(CorrelationData correlationData, String cause) {
                log.error("defaultConfirmCallback...");
            }
        };
    }

    @Bean
    @ConditionalOnMissingBean
    public ReturnsCallback defaultMyReturnsCallback() {
        return new ReturnsCallback() {
            @Override
            protected void compensate(ReturnedMessage returned) {
                log.error("defaultMyReturnsCallback...");
            }
        };
    }

    /**
     * 动态创建队列、交换机初始化器
     *
     * @return RabbitModuleInitializer
     */
    @Bean
    @ConditionalOnMissingBean
    public RabbitModuleInitializer rabbitModuleInitializer(AmqpAdmin amqpAdmin, RabbitModuleProperties rabbitModuleProperties) {
        return new RabbitModuleInitializer(amqpAdmin, rabbitModuleProperties);
    }

}
